package com.modules.test;

import java.util.List;
import java.util.Map;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;

public class JumpTaskCmd implements Command<Void> {
	public static final String	REJECT_TO_TOKEN	= "_rejectTo_";
	public static final String	REJECT_FROM_TOKEN	= "_rejectFrom_";
	public static final String	RE_CALL	= "_reCall_";
	protected Map<String, Object>	variables;
	private String					targetTaskKey;
	protected String				executionId;

	public JumpTaskCmd(String executionId, String targetTaskKey, Map<String, Object> variables) {
		this.executionId = executionId;
		this.variables = variables;
		this.targetTaskKey = targetTaskKey;
	}

	public Void execute(CommandContext commandContext) {
		//UserProfile user = ProfileContextHolder.getUserProfile();
		String fromTaskDefinitionKey = null;
		ExecutionEntity executionEntity = Context.getCommandContext().getExecutionEntityManager().findExecutionById(executionId);
		List<TaskEntity> taskList = Context.getCommandContext().getTaskEntityManager().findTasksByExecutionId(executionId);
		for (TaskEntity taskEntity : taskList) {
			//taskEntity.setAssignee(user != null ? user.getStaffCode() : null);
			taskEntity.setName(taskEntity.getName() + "|驳回");
			fromTaskDefinitionKey = taskEntity.getTaskDefinitionKey();
			//删除taskEntity
			Context.getCommandContext().getTaskEntityManager().deleteTask(taskEntity, "jump", false);
			//删除ExecutionEntity里的taskEntity
			executionEntity.removeTask(taskEntity);
		}
		ProcessDefinitionImpl processDefinition = executionEntity.getProcessDefinition();
		ActivityImpl activity = processDefinition.findActivity(targetTaskKey);
		//if(null == executionEntity.getVariable(BpmVariables.REJECT_TO_TOKEN)){
			executionEntity.setVariable(REJECT_TO_TOKEN, targetTaskKey);
		//}
		if(null == executionEntity.getVariable(REJECT_FROM_TOKEN)){
			executionEntity.setVariable(REJECT_FROM_TOKEN, fromTaskDefinitionKey);
		}
		executionEntity.executeActivity(activity);
		
		return null;
	}
}